<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>state状态机器</title>
    <link rel="icon" href="../favicon.ico">
    <script src="../react/react.development.js"></script>
    <script src="../react/react-dom.development.js"></script>
    <script src="../react/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
    class Clock extends React.Component {

        // es7中可以这样写，这是类的属性的书写方法
        state = {
            time: new Date()
        }

        // constructor (props) {
        //     super(props)
        //     this.state = {time: new Date()};
        // }

        // componentDidMount 是组件挂载生命周期函数
        componentDidMount () {
            this.timeID = setInterval(() => {
                this.tick()
            }, 1000)
        }

        // componentWillUnmount 是组件卸载的时候触发它
        componentWillUnmount () {
            clearInterval(this.timeID)
        }

        tick () {
            // 每次setState都会造成数据的重新渲染 可以理解为小程序中的setData()
            this.setState({
                time: new Date()
            })
        }

        render () {
            let { time } = this.state
            return (
                <div>
                    <h1>Clock</h1>
                    <h2>{time.toLocaleTimeString()}</h2>
                </div>
            )
        }
    }

    ReactDOM.render(<Clock></Clock>, document.getElementById('root'))
</script>
</body>
</html>
